package com.dp.gateway.filter;

import cn.hutool.core.bean.BeanUtil;
import com.dp.common.domain.dto.UserDTO;
import com.dp.gateway.config.AuthProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.dp.common.constants.RedisConstants.LOGIN_USER_KEY;
import static com.dp.common.constants.RedisConstants.LOGIN_USER_TTL;

@Component
public class DPGlobalFilter implements GlobalFilter {

    @Autowired
    private AuthProperties authProperties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 获取request
        ServerHttpRequest request = exchange.getRequest();
        // 2. 检查是否在白名单
        if (!isExclude(request.getPath().toString())) {
            return chain.filter(exchange);
        }
        // 3. 获取token并根据token从redis中获取用户信息
        List<String> headers = request.getHeaders().get("authorization");
        if (headers == null || headers.isEmpty()) {
            return chain.filter(exchange);
        }
        String token = headers.get(0);
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        // 4. 刷新token时间
        stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.SECONDS);
        // 5. 封装用户信息，传入下游服务器
        // 5.1 将userDTO序列化
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String userJson = objectMapper.writeValueAsString(userDTO);
            // 5.2 将信息传入下游
            ServerWebExchange swe = exchange.mutate()
                    .request(builder -> builder.header("user-info", userJson))
                    .build();
            return chain.filter(swe);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 名单过滤
     */
    private boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(path, excludePath)) {
                return true;
            }
        }
        return false;
    }
}
